import axios from "axios";
import qs from "qs";
import {Notification} from 'element-ui'

const service = axios.create({
    baseURL: "http://localhost:9999",
});

service.interceptors.request.use(config => {
    // 从localStorage中获取token
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    if (userInfo && userInfo.tokenValue) {
        // 将token设置到请求头中
        config.headers["satoken"] = `${userInfo.tokenValue}`;
    }
    return config;
})

service.interceptors.response.use(response => {
    let data = response.data;
    if (!data) {
        window.location.reload();
    }
    console.log(data)
    // 无权限
    if (data.code === 403) {
        Notification.error({
            title: '警告',
            message: data.message,
        });
        return;
    }
    // 登录过期
    if (data.code === 401) {
        Notification.warning({
            title: '警告',
            message: data.message,
        });
        setTimeout(() => {
            localStorage.removeItem("userInfo")
            window.location.reload();
        }, 1000)

        return;
    }
    return response.data
})


const http = {
    post(url, params) {
        return service.post(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                "Content-Type": "application/json"
            }
        })
    },

    get(url, params) {
        return service.get(url, {
            params: params,
            paramsSerializer: (params) => {
                return qs.stringify(params)
            }
        })
    },
}
export default http;
